@echo off

setlocal enabledelayedexpansion

IF [%1] EQU [] (
	echo USAGE: %0 classname [opts]
	EXIT /B 1
)

pushd %~dp0..
cd ..
set BASE_DIR=%CD%
popd

rem Classpath addition for release
for %%i in (%BASE_DIR%\lib\*) do (
	call :concat %%i
)

rem Log directory to use
IF ["%LOG_DIR%"] EQU [""] (
    set LOG_DIR=%BASE_DIR%/logs
)

rem create logs directory
IF not exist %LOG_DIR% (
  mkdir %LOG_DIR%
)

set DEFAULT_JAVA_DEBUG_PORT=5005
set DEFAULT_DEBUG_SUSPEND_FLAG=y
rem Set Debug options if enabled
IF ["%JAVA_DEBUG%"] NEQ [""] (


	IF ["%JAVA_DEBUG_PORT%"] EQU [""] (
		set JAVA_DEBUG_PORT=%DEFAULT_JAVA_DEBUG_PORT%
	)

	IF ["%DEBUG_SUSPEND_FLAG%"] EQU [""] (
		set DEBUG_SUSPEND_FLAG=%DEFAULT_DEBUG_SUSPEND_FLAG%
	)
	set DEFAULT_JAVA_DEBUG_OPTS=-agentlib:jdwp=transport=dt_socket,server=y,suspend=!DEBUG_SUSPEND_FLAG!,address=!JAVA_DEBUG_PORT!

	IF ["%JAVA_DEBUG_OPTS%"] EQU [""] (
		set JAVA_DEBUG_OPTS=!DEFAULT_JAVA_DEBUG_OPTS!
	)

	echo Enabling Java debug options: !JAVA_DEBUG_OPTS!
	set JAVA_OPTS=!JAVA_DEBUG_OPTS! !JAVA_OPTS!
)

rem Which java to use
IF ["%JAVA_HOME%"] EQU [""] (
	set JAVA=java
) ELSE (
	set JAVA="%JAVA_HOME%/bin/java"
)

rem Memory options
IF ["%JAVA_HEAP_OPTS%"] EQU [""] (
	set JAVA_HEAP_OPTS=-Xmx256M
)

rem JVM performance options
IF ["%JAVA_JVM_PERFORMANCE_OPTS%"] EQU [""] (
	set JAVA_JVM_PERFORMANCE_OPTS=-server -XX:SurvivorRatio=8 -XX:+UseConcMarkSweepGC -XX:+CMSParallelRemarkEnabled -XX:+UseCMSInitiatingOccupancyOnly -XX:+ScavengeBeforeFullGC -XX:+CMSScavengeBeforeRemark -XX:+HeapDumpOnOutOfMemoryError -XX:+DisableExplicitGC
)

IF ["%CLASSPATH%"] EQU [""] (
	echo Classpath is empty. Please build the project first e.g. by running 'gradlew jarAll'
	EXIT /B 2
)

set COMMAND=%JAVA% %JAVA_HEAP_OPTS% %JAVA_JVM_PERFORMANCE_OPTS% -Dlogging.path=%LOG_DIR%  -cp "%CLASSPATH%" %JAVA_OPTS% %*
rem echo.
rem echo %COMMAND%
rem echo.

%COMMAND%

goto :eof
:concat
IF ["%CLASSPATH%"] EQU [""] (
  set "CLASSPATH=%1"
) ELSE (
  set "CLASSPATH=%CLASSPATH%;%1"
)
